/* eslint-disable prefer-promise-reject-errors */
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import Helper from '../../../../../components/Helper';
import EmptyData from '../../../../../components/empty/EmptyData';
import notification from '@kuiper-components/notification';

import cn from 'classnames';
import fetchFer from 'API/fetch';
import { TimePicker, Spin } from 'antd';
import locale from 'antd/es/date-picker/locale/zh_CN';
import CheckboxGroup from '../../../../../components/CheckboxGroup/indexNew';
import Select from '@knownsec/react-component/dist/Select';
import Input from '@knownsec/react-component/dist/Input';
import Form from '@knownsec/react-component/dist/Form';
import Button from '@knownsec/react-component/dist/Button';
import moment from 'moment';
import Dialog from '@knownsec/react-component/dist/Dialog';
import Table from '@knownsec/react-component/dist/Table';

import s from './Content.module.css';
import { cloneDeep } from 'lodash';

import recursion from '../../../../../helpers/recursionForm';
const defaultData = {
	name: '',
	receivers: [],
	job_ids: [],
	notification: ['email', 'sms', 'wechat', 'in_box'],
	enable: ['security', 'availability', 'asset', 'host'],
	sms_allowed_time: { start: '00:00:00', end: '23:59:00' },
	email_allowed_time: { start: '00:00:00', end: '23:59:00' },
	email_daily_limit: 10,
	sms_daily_limit: 10,
};
const alertOptions = [
	{ label: '邮件', value: 'email' },
	{ label: '短信', value: 'sms' },
	{ label: '微信', value: 'wechat' },
	{ label: '站内信', value: 'in_box' },
];
const monitorOptions = [
	{ label: 'Web安全监测', value: 'security' },
	{ label: '可用性监测', value: 'availability' },
	{ label: '资产变动监测', value: 'asset' },
	{ label: '主机安全监测', value: 'host' },
];

export default function Content({ submit, record, isDefault, onClose }) {
	const [form] = Form.useForm();
	const [timeObj, setTimeObj] = useState({
		smsST: moment('00:00:00', 'HH:mm:ss'),
		smsET: moment('23:59:59', 'HH:mm:ss'),
		emailST: moment('00:00:00', 'HH:mm:ss'),
		emailET: moment('23:59:59', 'HH:mm:ss'),
	});
	const [jobList, setJobList] = useState([]);
	const [loadingForm, setLoadingForm] = useState(true);
	const [userList, setUserList] = useState([]);
	const [diffList, setDiffList] = useState([]);
	const [diffText, setDiffText] = useState('');
	const [jobShow, setJobShow] = useState(false);

	const getAsset = async () => {
		setLoadingForm(true);
		const assetList = await fetchFer(`/api/v2/asset/verified-asset?asset_type=all`, {
			method: 'GET',
		});
		const list = assetList.data.JobMany.map(item => {
			return {
				label: item.note + '\t' + item.targetUrl,
				labelHtml: `<span style="width: 100px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" title='${item.note}'>${item.note}</span>
 <span style="width: 200px;display: inline-block;margin-left: 10px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" title='${item.targetUrl}'>${item.targetUrl}</span>`,
				value: item.id,
			};
		});
		setLoadingForm(false);
		setJobList(list);
	};
	const getUserList = async () => {
		const userList = await fetchFer(`/api/v2/alerts/alert_strategy_receivers`, {
			method: 'GET',
		});
		if (userList.status === 'success') {
			const list = userList.data.map(item => {
				return {
					label: item.name,
					value: item.id,
				};
			});
			setUserList(list);
			setLoadingForm(false);
		}
	};
	const getFormData = async () => {
		const url = `/api/v2/alerts/alert_strategy_detail?alert_group_id=${record.id}`;
		const res = await fetchFer(url, {
			method: 'GET',
		});
		const data = res.data;
		form.setFieldsValue(data);
		setTimeObj({
			smsST: moment(data.sms_allowed_time.start, 'HH:mm:ss'),
			smsET: moment(data.sms_allowed_time.end, 'HH:mm:ss'),
			emailST: moment(data.email_allowed_time.start, 'HH:mm:ss'),
			emailET: moment(data.email_allowed_time.end, 'HH:mm:ss'),
		});
	};
	const diffJob = data => {
		form.validateFields().then(async res => {
			const url = `/api/v2/alerts/alert_strategy_jobs_comp`;
			const params = { job_ids: res.job_ids };
			if (record) {
				params.alert_group_id = record.id;
			}
			const diffRes = await fetchFer(url, {
				method: 'POST',
				body: JSON.stringify(params),
			});
			if (diffRes.status === 'success') {
				if (diffRes.data.length) {
					let text =
						'以下资产在于其他告警策略中，确认后资产将会从对应告警策略中移除，您确定要新建策略吗？';
					setDiffList(diffRes.data);
					setJobShow(true);
					if (record) {
						const diffType = diffRes.data.some(e => {
							return e.type === 'remove';
						});
						text = diffType
							? '以下资产在此次中被删除，删除后资产将不会进行告警，您确定要修改策略吗？'
							: '以下资产在被删除告警通知或者从旧告警策略移除动作，您确定要修改当前策略吗？';
					}
					setDiffText(text);
				} else {
					subForm();
				}
			}
		});
	};
	const subForm = async () => {
		const params = form.getFieldsValue();
		let url = '';
		if (record) {
			params.alert_group_id = record.id;
			url = '/api/v2/alerts/edit_alert_strategy';
		} else {
			url = '/api/v2/alerts/add_alert_strategy';
		}
		const subRes = await fetchFer(url, {
			method: 'POST',
			body: JSON.stringify(params),
			checkStatus: 501,
		}).catch(e => {});
		form.resetFields();
		if (subRes.status === 'success') {
			notification.success({
				message: `保存成功`,
				placement: 'top',
			});
			submit();
		} else {
			notification.error({
				message: '保存失败',
				description: subRes.msg,
				placement: 'top',
			});
		}
	};
	// 表单值绑定
	const onValues = (data, allValues) => {
		const values = recursion(data);
		if (values.email_daily_limit) {
			const email = ~~values.email_daily_limit;
			values.email_daily_limit = email <= 0 ? 0 : email + '';
		}
		if (values.sms_daily_limit) {
			const sms = ~~values.sms_daily_limit;
			values.sms_daily_limit = sms <= 0 ? 0 : sms + '';
		}
		form.setFieldsValue(values);
	};
	// 验证
	const validatormap = (rule, value = {}) => {
		if (rule.field === 'job_ids') {
			if (!value[0]) {
				return Promise.reject('资产地址不能为空');
			} else if (value.length > 100) {
				return Promise.reject('资产地址不超过100个');
			}
		}
		if (rule.field === 'receivers') {
			if (!value[0]) {
				return Promise.reject('告警人不能为空');
			}
		}
		if (rule.field === 'name') {
			if (!value) {
				return Promise.reject('请输入任务名称');
			} else if (value.length > 50) {
				return Promise.reject('任务名称不超过50个字符');
			}
		}
		return Promise.resolve();
	};
	const ChangeTime = (e, type) => {
		const timeObj_ = cloneDeep(timeObj);
		timeObj_[type] = moment(e, 'HH:mm:ss');
		setTimeObj(timeObj_);
		if (type.includes('sms')) {
			const sms_time = form.getFieldValue('sms_allowed_time');
			const num = type === 'smsST' ? 'start' : 'end';
			sms_time[num] = type === 'smsST' ? e + ':00' : e + ':59';
			form.setFieldsValue(sms_time);
		} else {
			const email_time = form.getFieldValue('email_allowed_time');
			const num = type === 'emailST' ? 'start' : 'end';
			email_time[num] = type === 'emailST' ? e + ':00' : e + ':59';
			form.setFieldsValue(email_time);
		}
	};
	const columnsJod = [
		{
			title: '资产名称',
			dataIndex: 'note',
			key: 'note',
		},
		{
			title: '资产地址',
			dataIndex: 'target_url',
			key: 'target_url',
		},
		{
			title: '源站IP',
			dataIndex: 'source_ip',
			key: 'source_ip',
			render(source_ip, record) {
				return <span>{source_ip || '- -'}</span>;
			},
		},
		{
			title: '动作',
			dataIndex: 'type',
			key: 'type',
			render(type, record) {
				return <span>{type === 'remove' ? '删除' : '移除旧策略'}</span>;
			},
		},
	];
	useEffect(() => {
		getAsset();
		getUserList();
		if (record) {
			getFormData();
		}
	}, []);
	return (
		<Spin spinning={loadingForm}>
			<Form
				form={form}
				labelCol={{
					span: 6,
				}}
				wrapperCol={{
					span: 18,
				}}
				style={{ opacity: jobShow ? 0 : 1 }}
				initialValues={defaultData}
				onValuesChange={(newItem, allValues) => {
					onValues(newItem, allValues);
				}}
				className={s.content}
			>
				<dov className={s.formBox}>
					<Form.Item
						label="策略名称"
						name="name"
						rules={[
							{
								required: true,
								validator: validatormap,
							},
						]}
					>
						<Input
							className={s.w420}
							placeholder="请输入策略名称"
							autoComplete={'off'}
							disabled={isDefault}
						/>
					</Form.Item>
					<Form.Item
						label="告警人"
						name="receivers"
						rules={[
							{
								required: true,
								validator: validatormap,
							},
						]}
					>
						<Select
							className={cn(s.w420, s.select)}
							placeholder="请选择告警人"
							option={userList}
							checkAll
							multiple
							searchable
							clearable
						/>
					</Form.Item>
					<div className={s.item}>
						<Form.Item
							label="告警资产"
							name="job_ids"
							rules={[
								{
									required: true,
									validator: validatormap,
								},
							]}
						>
							<Select
								className={cn(s.w420, s.select)}
								placeholder="请选择资产地址"
								option={jobList}
								checkAll
								multiple
								searchable
								clearable
							/>
						</Form.Item>
						<div className={s.icons}>
							<Helper
								overlay="一个资产只能对应一个告警策略，若所选资产存在于其他告警策略中，则新建策略时资产将从对应告警策略中移除。"
								placement="top"
							/>
						</div>
					</div>
					<Form.Item label="通知类型" name="notification">
						<CheckboxGroup options={alertOptions} single={false} />
					</Form.Item>
					<Form.Item label="告警类型" name="enable">
						<CheckboxGroup options={monitorOptions} single={false} />
					</Form.Item>
					<Form.Item label="短信生效时间" name="sms_allowed_time">
						<div>
							<TimePicker
								placeholder="请选择时间"
								locale={locale}
								value={timeObj.smsST}
								className={s.mr1r}
								format={'HH:mm'}
								allowClear={false}
								getPopupContainer={triggerNode => triggerNode}
								onChange={(time, timeString) => {
									ChangeTime(timeString, 'smsST');
								}}
							/>
							~
							<TimePicker
								format={'HH:mm'}
								placeholder="请选择时间"
								locale={locale}
								value={timeObj.smsET}
								className={s.ml1r}
								allowClear={false}
								getPopupContainer={triggerNode => triggerNode}
								onChange={(time, timeString) => {
									ChangeTime(timeString, 'smsET');
								}}
							/>
						</div>
					</Form.Item>
					<Form.Item label="邮件生效时间" name="email_allowed_time">
						<div>
							<TimePicker
								format={'HH:mm'}
								placeholder="请选择时间"
								locale={locale}
								value={timeObj.emailST}
								className={s.mr1r}
								allowClear={false}
								getPopupContainer={triggerNode => triggerNode}
								onChange={(time, timeString) => {
									ChangeTime(timeString, 'emailST');
								}}
							/>
							~
							<TimePicker
								format={'HH:mm'}
								placeholder="请选择时间"
								value={timeObj.emailET}
								locale={locale}
								allowClear={false}
								className={s.ml1r}
								getPopupContainer={triggerNode => triggerNode}
								onChange={(time, timeString) => {
									ChangeTime(timeString, 'emailET');
								}}
							/>
						</div>
					</Form.Item>
					<div className={s.item}>
						<Form.Item label="每日短信告警上限" name="sms_daily_limit">
							<Input className={s.maxInp} placeholder="请输入上限" />
						</Form.Item>
						<p className={s.iconsText}>条</p>
					</div>
					<div className={s.item}>
						<Form.Item label="每日邮件告警上限" name="email_daily_limit">
							<Input
								className={s.maxInp}
								placeholder="请输入上限"
								autoComplete={'off'}
							/>
						</Form.Item>
						<p className={s.iconsText}>条</p>
					</div>

					<div className={s.bottomBtn}>
						<Button
							className={s.mr1r}
							onClick={() => {
								form.resetFields();
								onClose();
							}}
						>
							取消
						</Button>
						<Button
							type="primary"
							className={s.ml1r}
							onClick={() => {
								diffJob();
							}}
						>
							确定
						</Button>
					</div>
				</dov>
			</Form>
			<Dialog
				visible={jobShow}
				key={Date.now()}
				onhide={() => setJobShow(false)}
				title="告警资产详情"
				cancelText="取消"
				confirmText="确认"
				className={cn(s.w700)}
				onsubmit={() => {
					subForm();
				}}
			>
				<div className={cn(s.p20, s.mh65p, s.ofa)}>
					<p className={s.text}>{diffText}</p>
					<Table
						key={Date.now()}
						pro
						empty={<EmptyData type={'img'} className={s.nobor} />}
						columns={columnsJod}
						data={diffList}
					/>
				</div>
			</Dialog>
		</Spin>
	);
}

Content.propTypes = {
	record: PropTypes.any,
	receiver: PropTypes.shape({
		name: PropTypes.string.isRequired,
	}),
	submit: PropTypes.func,
	update: PropTypes.func.isRequired,
	value: PropTypes.shape({
		_id: PropTypes.string.isRequired,
		includeWechat: PropTypes.bool,
		receiverIds: PropTypes.arrayOf(PropTypes.string),
		receivers: PropTypes.arrayOf(
			PropTypes.shape({
				_id: PropTypes.string,
			})
		),
	}),
	receivers: PropTypes.arrayOf(
		PropTypes.shape({
			_id: PropTypes.string.isRequired,
			name: PropTypes.string.isRequired,
		})
	),
	wechat: PropTypes.shape({
		nickname: PropTypes.string,
		wx_openid: PropTypes.string,
	}),
	defaultReceiver: PropTypes.shape({
		_id: PropTypes.string,
	}),
	isDefault: PropTypes.bool,
	onClose: PropTypes.func,
};

Content.defaultProps = {
	receivers: [],
	isDefault: false,
};
